﻿// description  : 业务核心领域模型
// author       : tristan
// created      : 2011/2/17
// contact      : snaprack@gmail.com


namespace RBAC
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Data.SqlClient;

    /// <summary>
    /// 账户
    /// </summary>
    public partial class Account
    {
        const string DEFAULT_PASSWORD = "123456";
        /// <summary>
        /// 获得实体容器
        /// </summary>
        public EntityContext GetEntityContext()
        {
            return EntityContext.GetInstance();
        }
        /// <summary>
        /// 默认的账户密码
        /// </summary>
        public static string DefaultPassword
        {
            get
            {
                string config = System.Configuration.ConfigurationManager.AppSettings["defaultPassword"];
                return string.IsNullOrEmpty(config) ? DEFAULT_PASSWORD : config;
            }
        }
        /// <summary>
        /// 获得账户指派的所有角色
        /// </summary>
        public IEnumerable<Role> GetRoles()
        {
            return GetEntityContext().GetRolesByAccount(this.ID);
        }
        /// <summary>
        /// 指派新角色
        /// </summary>
        /// <param name="role">角色</param>
        public void Assign(string role)
        {
            Role r = GetEntityContext().Roles.FirstOrDefault(it => it.ID == role);
            if (r != null)
            {
                Actor actor = new Actor { Account = this, Role = r };
                GetEntityContext().AddToActors(actor);
            }
        }
        /// <summary>
        /// 解除角色指派
        /// </summary>
        /// <param name="role">角色</param>
        public void Unassign(string role)
        {
            Actor actor = GetEntityContext().Actors.FirstOrDefault(it => it.Account.ID == this.ID && it.Role.ID == role);
            if (actor != null)
            {
                GetEntityContext().DeleteObject(actor);
            }
        }
        /// <summary>
        /// 载入指定的账户实例
        /// </summary>
        /// <param name="id">账户标识，不区分大小写</param>
        public static Account Load(string id)
        {
            return Find(user => user.ID.Equals(id, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
        }

        /// <summary>
        /// 载入所有的账户实例
        /// </summary>
        /// <returns></returns>
        public static IQueryable<Account> LoadAll()
        {
            Account account = new Account();
            return account.GetEntityContext().Accounts;
        }
        /// <summary>
        /// 查询账户实例
        /// </summary>
        /// <param name="predicate">查询条件</param>
        public static IQueryable<Account> Find(Expression<Func<Account, bool>> predicate)
        {
            Account account = new Account();
            return account.GetEntityContext().Accounts.Where(predicate);
        }
        /// <summary>
        /// 添加账户
        /// </summary>
        public void Add()
        {
            GetEntityContext().AddToAccounts(this);
        }
        /// <summary>
        /// 删除账户
        /// </summary>
        public void Remove()
        {
            GetEntityContext().DeleteObject(this);
        }
        /// <summary>
        /// 保存更改
        /// </summary>
        public void Save()
        {
            try
            {
                GetEntityContext().SaveChanges();
            }
            catch (Exception e)
            {
                Error(e);
            }
        }
        /// <summary>
        /// 处理异常
        /// </summary>
        public virtual void Error(Exception e)
        {
            Exception baseException = e.GetBaseException();
            if (baseException is SqlException
                && baseException.Message.Contains("违反了 PRIMARY KEY 约束"))
            {
                throw new AccessControlException("添加失败, 账户已经存在!", baseException);
            }
        }
    }

}